package student.action;

import java.io.FileOutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

import student.actionform.OutcomeForm;
import util.Encoding;
import dao.OutcomeMagDao;
import dao.impl.OutcomeMagImpl;
import domain.Outcome;
import domain.Student;

/**
 * 
 * Jun 5, 2009
 *
 * @author Fabian
 *
 */
public class ManagerOutcomeAction extends DispatchAction {
	
	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		int hw_id = Integer.parseInt(request.getParameter("hw_id"));
		OutcomeForm of = new OutcomeForm();
		int start = Integer.parseInt(request.getParameter("start"));//of.getStart();
		int limit = Integer.parseInt(request.getParameter("limit"));//of.getLimit();
		
		OutcomeMagDao omd = new OutcomeMagImpl();
		
		String resultArray = "";
		
		List<Outcome> list = omd.getPageOutcome(start, limit, hw_id);
		int totalCount = omd.getTotalCount(hw_id);		
		
		for (Iterator<Outcome> it = list.iterator(); it.hasNext(); ) {
			Outcome o = it.next();
			Date pub_time = o.getPub_time();	
			long p = pub_time.getTime();
							
			resultArray = resultArray + "{id: " + o.getId() + ", stu_name: '" + o.getStu_name() + "', format:'" + o.getFormat() + 
										"', size:'" + o.getSize() + "', path:'" + o.getPath() + "', visto_path:'" + o.getVisto_path() +
										"', pub_time: new Date(" + p + "), is_visto:'" + o.getIs_visto() + "', score: '" + o.getScore() + 
										"', postil: '" + o.getPostil() + "'}";
			if (it.hasNext()) {
				resultArray = resultArray + ",";
			}			
		}
		
		
		String jsonStr = "";
		jsonStr = "{totalProperty: " + totalCount + ", root: [ " + resultArray + " ]}";
		
		request.setAttribute("result", jsonStr);
				
		return mapping.findForward("show_result");
	}
	
	/**
	 * 添加作业
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		Student stu = (Student)request.getSession().getAttribute("user");
		int stu_id = stu.getId();		
		String stu_name = stu.getName();		
		
		OutcomeForm of = (OutcomeForm)form;
		int hw_id = of.getId();
		FormFile file = of.getFile_path();
		
		//设置文件名				
		String dir = servlet.getServletContext().getRealPath("/");
		String fileName = Encoding.gbkToUTF(file.getFileName());		//解决乱码问题
		//获取扩展名
		String format = fileName.substring((fileName.lastIndexOf('.') + 1));
		if (format.length() > 4) {
			format = fileName.substring(fileName.length()-3);
		}
		//给file一个新的名字，使用UUID
		String newfileName = UUID.randomUUID().toString() + "." + format;
		
		String size = "";
		int theSize = file.getFileSize();
		int fileSize = 0;
		if (theSize > 1024) {
			fileSize = (theSize)/1024;
			size = fileSize + " KB";
		} else {
			fileSize = theSize;
			size = fileSize + " B";
		}
		
		FileOutputStream fos = new FileOutputStream(dir + "resource/outcome/" + newfileName);
		fos.write(file.getFileData());
		fos.flush();
		fos.close();
		
		
		String filePath = "resource/outcome/" + newfileName;
		
		//更新数据库
		Outcome o = new Outcome();
		o.setHw_id(hw_id);
		o.setStu_id(stu_id);
		o.setStu_name(stu_name);
		o.setFormat(format);	
		o.setSize(size);
		o.setPath(filePath);
		o.setIs_visto("未批改");
		
		OutcomeMagDao omd = new OutcomeMagImpl();
		boolean result = omd.addOutcome(o);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{success: true, msg: '恭喜，提交作业解答成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{failure: true, msg: '抱歉，提交作业解答失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		
		return mapping.findForward("add_result");
	}
	
	/**
	 * 添加老师批改过的作业解答
	 */
	public ActionForward addVisto(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		OutcomeForm of = (OutcomeForm)form;
		int o_id = of.getId();
		FormFile file = of.getFile_path();
		
		//设置文件名				
		String dir = servlet.getServletContext().getRealPath("/");
		String fileName = Encoding.gbkToUTF(file.getFileName());		//解决乱码问题
		//获取扩展名
		String format = fileName.substring((fileName.lastIndexOf('.') + 1));
		if (format.length() > 4) {
			format = fileName.substring(fileName.length()-3);
		}
		//给file一个新的名字，使用UUID
		String newfileName = UUID.randomUUID().toString() + "." + format;
		
		String size = "";
		int theSize = file.getFileSize();
		int fileSize = 0;
		if (theSize > 1024) {
			fileSize = (theSize)/1024;
			size = fileSize + " KB";
		} else {
			fileSize = theSize;
			size = fileSize + " B";
		}
		
		FileOutputStream fos = new FileOutputStream(dir + "resource/outcomeVisto/" + newfileName);
		fos.write(file.getFileData());
		fos.flush();
		fos.close();
		
		
		String filePath = "resource/outcomeVisto/" + newfileName;
		
		//更新数据库
		Outcome o = new Outcome();
		o.setId(o_id);
		o.setVisto_path(filePath);
		o.setIs_visto("已批改");
		
		OutcomeMagDao omd = new OutcomeMagImpl();
		boolean result = omd.addVistoOutcome(o);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{success: true, msg: '恭喜，提交已批阅作业解答成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{failure: true, msg: '抱歉，提交已批阅作业解答失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		
		return mapping.findForward("addVisto_result");
	}
	
	/**
	 * 获取某个作业的解答
	 */
	public ActionForward get(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		int hw_id = Integer.parseInt(request.getParameter("hw_id"));
		OutcomeForm of = new OutcomeForm();
		/*int start = of.getStart();
		int limit = of.getLimit();*/
		
		Student stu = (Student)request.getSession().getAttribute("user");
		int stu_id = stu.getId();		
		
		OutcomeMagDao omd = new OutcomeMagImpl();
		Outcome o = omd.getOutcome(hw_id, stu_id);
		
		Date put_time = o.getPub_time();
		long lpt = put_time.getTime();
		
		//组装JSON字符串，返回
		String resultArray = "";
		resultArray = "{format: '" + o.getFormat() + "', size: '" + o.getSize() + "', visto_path: '" + o.getVisto_path() +
							"', pub_time: new Date(" + lpt + "), is_visto: '" + o.getIs_visto() +
							"', score: '" + o.getScore()+ "', postil: '" + o.getPostil() + "'}";;
		
		String jsonStr = "";
		jsonStr = "{totalProperty: 1, root: [ " + resultArray + " ]}";
		
		request.setAttribute("result", jsonStr);
		
		return mapping.findForward("get_result");
	}
	
	/**
	 * 作业打分/评语
	 */
	public ActionForward mark(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		
		OutcomeForm of = (OutcomeForm)form;
		int id = of.getId();
		String score = of.getScore();
		String postil = of.getPostil();
		
		Outcome o = new Outcome();
		o.setId(id);
		o.setScore(score);
		o.setPostil(postil);
		
		OutcomeMagDao omd = new OutcomeMagImpl();
		boolean result = omd.markOutcome(o);		
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{success: true, msg: '恭喜，评判作业成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{failure: true, msg: '抱歉，评判作业失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		
		return mapping.findForward("mark_result");
	}
}
